<?php

/**
 * 检测朋友圈外链是否被封；替换被封外链
 */

include __DIR__ . '/g1.php';

$sec   = 10;   //每次查询拦截时暂停时长，单位：秒
$db    = get_db_connect();
$query = $db->query("SELECT id, opts FROM public.plan WHERE status = 1 ORDER BY id DESC");

while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
    $opts    = json_decode($row['opts'], true);
    $devices = $opts['devices'] ?? null;

    if (empty($devices)) {
        continue;
    }

    $device = array_shift($devices);

    if (!$tmp = parse_url($device['url'])) {
        continue;
    }

    /**
     * 忽略微信公众号文章
     */
    if ($tmp['host'] == WEIXIN_MP_URL) {
        continue;
    }

    sleep($sec);
    $msg = check_domain_intercept($device['url']);

    /**
     * 截止到2016.12.27所有投放设备的网址是一样的
     * 所以只检测一条即可
     * 而且当前计费系统只应用于微信量
     */
    if (trim($msg['msg']) == '域名正常') {
        continue;
    }

    while ($newUrl = get_allow_bak_url($row['id'])) {
        sleep($sec);

        $msg    = check_domain_intercept($newUrl);
        $status = in_array(trim($msg['msg']), ['域名被封', '域名正常，分享朋友圈不可见'])
                  ? 'HOLD'
                  : 'USE';
             
        hold_bak_url($row['id'], $newUrl, $status, $msg['msg']);

        if ($status == 'USE') {
            change_plan_url($row['id'], $newUrl);

            break;
        }
    }
}

exit('finish!');
